package com.leyou.job;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.leyou.config.OSSProperties;
import com.leyou.constant.RedisConstant;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@JobHandler(value = "cleanBrandImage")
public class CleanImages extends IJobHandler {

    @Autowired
    private OSSProperties prop;


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public ReturnT<String> execute(String s) throws Exception {

        Set<String> difference = redisTemplate.opsForSet().difference(RedisConstant.BRAND_IMAGE, RedisConstant.BRAND_DB_IMAGE);

        if (difference.size() > 0) {

            for (String filename : difference) {
                // 切割字符串，只需要文件夹/文件名
                filename = StringUtils.substringAfter(filename,"com/");

                // 创建OSSClient实例
                OSS ossClient = new OSSClientBuilder().build(prop.getEndpoint(),prop.getAccessKeyId(),prop.getAccessKeySecret());

                ossClient.deleteObject(prop.getBucketName(), filename);

                // 关闭OSSClient
                ossClient.shutdown();
            }
            //  删除 redis上的两个集合
            redisTemplate.delete(RedisConstant.BRAND_IMAGE);
            redisTemplate.delete(RedisConstant.BRAND_DB_IMAGE);

            System.out.println("-setmeal--is-scanning---one-more");
        }
        System.out.println("-xxl-job--is-running----");
        return SUCCESS;
    }

}
